package com.mishow.utils;

import java.util.Properties;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import com.alibaba.fastjson.JSON;
import com.mishow.R;
import com.mishow.activity.MainActivity;
import com.mishow.activity.WebViewActivity;
import com.mishow.activity.WelcomeActivity;
import com.mishow.bean.PushMessageBean;
import com.mishow.log.MyLog;
import com.mishow.preferenses.SharedPreferencesUtil;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

/**
 * 
 * 作者：wei.miao<br/>
 * 描述：处理接收极光推送消息
 */
public class PushManagerUtil {

	/**
	 * 消息类型-打开应用
	 **/
	public static final int TYPE_OPEN_APP = 0;
	/**
	 * 消息类型-收到系统消息
	 **/
	public static final int TYPE_SYSTEM_MESSAGE = 202;

	/**
     * 消息类型-收到活动推送
     **/
    public static final int TYPE_GET_ACTIVITY = 301;
	/**
	 * 增加通用跳转类型(根据后台配置可跳转到大部分原生界面,包括webview等)
	 **/
	public static final int TYPE_HYPER_JUMP = 999;
	/**
     * 消息中心红点变化
     */
    public static final String ACTION_MINE_NEW = "com.mishow.message";
	
	private Context mContext;
	/** NotificationManager对象 **/
	private static NotificationManager nm;
	private SharedPreferencesUtil userInfoPf;
	/** 当前api版本 **/
	private static int currentapiVersion = android.os.Build.VERSION.SDK_INT;

	public PushManagerUtil(Context mContext) {
		this.mContext = mContext;
		nm = (NotificationManager) mContext
				.getSystemService(Activity.NOTIFICATION_SERVICE);
		userInfoPf = new SharedPreferencesUtil(mContext);
	}

	/**
	 * 获取并处理极光推送过来的消息
	 * 
	 * @param message
	 *            -[消息内容]
	 * @param customContentString
	 *            -[自定义消息内容]
	 */
	public void dispathMessage(String message, String customContentString) {
		MyLog.d("message>>>", message);
		// 推送消息内容
		PushMessageBean bean = getMessage(message);
		if (bean == null) {
			return;
		}
		/** 通知栏消息id **/
		String currentTimeMillis = System.currentTimeMillis() + "";
		int notificationId = Integer.parseInt(currentTimeMillis.substring(6,
				currentTimeMillis.length()));
		MyLog.d("notificationId>>>", notificationId + "");
		switch (bean.getCustom_content().getPushType()) {
		case TYPE_OPEN_APP:// 打开应用
			showOpenAppNotice(bean.getTitle(), bean.getDescription());
			break;
		case TYPE_SYSTEM_MESSAGE://系统消息
			mContext.sendOrderedBroadcast(new Intent(ACTION_MINE_NEW), null);
			 //首页显示红点
			userInfoPf.setHomeRedMessage(true);
			break;
		case TYPE_HYPER_JUMP: // 跳转类型推送
			JSONObject jsonObject;
			try {
				jsonObject = new JSONObject(bean.getCustom_content()
						.getPushContent());
				String adPgCode = jsonObject.getString("adPgCode");

				if (TextUtils.isEmpty(adPgCode)) {
					return;
				}
				// 根据不同adPgCode值,跳转不同页面
				Properties prop = OpenActivityManager.loadConfig(mContext,
						OpenActivityManager.FILE_NAME);

				int notificationCode = generateCode(adPgCode);

				String pushContent = "";
				try {
					JSONObject contentJson = new JSONObject(
							jsonObject.getString("adPageParam"));
					if (!jsonObject.isNull("userMerssageId")) {
						contentJson.put("userMerssageId",
								jsonObject.getString("userMerssageId"));// userMerssageId
																		// -_-!
					}
					if (!jsonObject.isNull("activityType")) {
						contentJson.put("activityType",
								jsonObject.getInt("activityType"));
					}
					pushContent = contentJson.toString();
				} catch (JSONException e) {
					e.printStackTrace();
				}

				showNotices(
						mContext,
						bean.getTitle(),
						bean.getDescription(),
						TYPE_HYPER_JUMP,
						pushContent,
						notificationId,
						notificationCode,
						prop.getProperty(adPgCode + "",
								MainActivity.class.getName()));

			} catch (Exception e1) {
				e1.printStackTrace();
			}

			break;
		default:
			break;
		}
	}

	/**
	 * 将后台推送的消息进行解析
	 * 
	 * @param messageStr
	 *            -[消息内容]
	 * @return PushMessageBean
	 */
	private PushMessageBean getMessage(String messageStr) {
		PushMessageBean bean = null;
		try {
			bean = JSON.parseObject(messageStr, PushMessageBean.class);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return bean;
	}

	/**
	 * 显示通知，点击后打开app
	 */
	private void showOpenAppNotice(String title, String content) {
		// 设置点击通知后的跳转
		Intent intent = new Intent(Intent.ACTION_MAIN);
		intent.addCategory(Intent.CATEGORY_LAUNCHER);
		intent.setClass(mContext, WelcomeActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
		PendingIntent appIntent = PendingIntent.getActivity(mContext, UUID
				.randomUUID().hashCode(), intent,
				PendingIntent.FLAG_UPDATE_CURRENT);

		NotificationCenter.getInstance().showNotification(mContext, title,
				content, appIntent, 0, getSmallIcon(), R.drawable.app_icon);
	}

	private static int getSmallIcon() {
		boolean useWhiteIcon = (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP);
		return useWhiteIcon ? R.drawable.ic_notification : R.drawable.app_icon;
	}

	@SuppressLint("NewApi")
	public static void showNotices(Context mContext, String title,
			String tickerText, int pushType, String pushContent,
			int notificationId, int adPageCode, String targetPackage) {

		// 设置点击通知后的跳转
		Intent notifyIntent = new Intent();
		ComponentName component = new ComponentName(mContext.getPackageName(),
				targetPackage);
		notifyIntent.setComponent(component);
		notifyIntent.putExtra("pushType", pushType);
		notifyIntent.putExtra("pushContent", pushContent);
		notifyIntent.putExtra("isFromNotice", true);

		// 活动传递参数
		if (pushType == TYPE_GET_ACTIVITY) {
			try {
				JSONObject jo = new JSONObject(pushContent);
				// 传参跳转到webview
				notifyIntent.putExtra("activityId", jo.getInt("activityId"));
				notifyIntent.putExtra("urlType",
						WebViewActivity.TYPE_ACTIVITY_FROMNOTICE);
				notifyIntent.putExtra("entranceType", "1");
				notifyIntent.putExtra("url", jo.getString("url"));// 增加直接对url处理
				if (jo.getString("title") != null
						&& !jo.getString("title").equals("")) {

					notifyIntent.putExtra("titleStr", jo.getString("title"));
				}

			} catch (JSONException e) {
				e.printStackTrace();
			}
		}  else if (pushType == TYPE_HYPER_JUMP) { // 通用跳转类型

			OpenActivityManager manager = new OpenActivityManager(mContext);
			manager.initIntentExtras(notifyIntent, "" + adPageCode, pushContent);

		}

		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
				| Intent.FLAG_ACTIVITY_CLEAR_TOP);

		PendingIntent appIntent = null;
		if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB
				&& !(AndroidUtil.getCurrentPackageName(mContext, false) + ".ui.MainActivity")
						.equals(targetPackage)) {
			Intent intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_LAUNCHER);
			intent.setClass(mContext, WelcomeActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
					| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
			appIntent = PendingIntent.getActivities(mContext
					.getApplicationContext(), UUID.randomUUID().hashCode(),
					new Intent[] { intent, notifyIntent },
					PendingIntent.FLAG_UPDATE_CURRENT);
		} else {
			appIntent = PendingIntent.getActivity(mContext
					.getApplicationContext(), UUID.randomUUID().hashCode(),
					notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		}

		// Notification nf = new Notification();
		// // 通知可以被clear
		// nf.flags = Notification.FLAG_AUTO_CANCEL;
		// // 通知的标题
		// nf.icon = R.drawable.app_notice_icon;
		// // 通知的内容
		// nf.tickerText = tickerText;
		// // 使用默认提示声音和默认手机震动
		// nf.defaults = Notification.DEFAULT_SOUND |
		// Notification.DEFAULT_VIBRATE;
		// nf.setLatestEventInfo(mContext, title, tickerText, appIntent);
		// nm.cancel(notificationId);
		// // nm.cancel(0);// 取消后台通知
		// nm.notify(notificationId, nf);

		// showNotification(mContext,title,tickerText,appIntent,notificationId,);

		NotificationCenter.getInstance().showNotification(mContext, title,
				tickerText, appIntent, notificationId, getSmallIcon(),
				R.drawable.app_icon);
	}
	
	private int generateCode(String adPgCode) {
        int result = 0;
        try {
            String codeString = adPgCode.substring(adPgCode.indexOf("_") + 1);
            result = Integer.parseInt(codeString);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return result;
    }

}
